<?php    

/**
 * 这是二开的扩展类，直接集中在这里，可以使用m('extends')进行调用 , 这里完全参照人人商城目录进行构建
 */
if (!(defined('IN_IA'))) 
{
	exit('Access Denied');
}

class Extends_EweiShopV2Model
{
    /**
     * 当触发了团购完成的操作
     * 团购订单表： ims_ewei_shop_groups_order
     * 用户订单表（包括团长）： ims_ewei_shop_member
     * @param integer $orderId 团购订单表中的id
     * @param float $credit 请严格按照要求传参 , 如果添加的是积分的话 ，则该参数必须大于1 ， 否则为余额， 必须小于 小于 1 大于或者等于 0.1 
     * @param string $creditType 增加的类型【积分：credit1、余额：credit2】 : /framework/model/cache.mod.php , 默认是增加余额
     * @return bool 
     */
    public function TeamToUpdateUserBalance($orderId , $credit='0.5' , $creditType='credit2')
    {  
        # -------方法调用--------------- 
        $this->TeamToUpdateUserBalance('25','0.05');
        # ----------------------

        $order = pdo_fetch("SELECT teamid as totalPrice FROM `ims_ewei_shop_groups_order` where id=$orderId and is_team=1"); # 必须存在 且 是团
        
        if( $order && !empty($order)) {
            $teamid = $order['teamid'];

            # 团长id
            $user = pdo_fetch("select openid,nickname from ims_ewei_shop_member where openid=(SELECT openid FROM ims_ewei_shop_groups_order where teamid=:teamid order by createtime ASC limit 1)",array(':teamid'=>$teamid));
            $openid = $user['openid'];

            # 增加余额 或者 积分
            # 这里判断是否是积分还是余额
            if( $creditType = 'credit2' ) { # 默认是余额
                if( $credit < 1 && $credit > 0.01 ) {
                     # 获取当前订单的总金额
                     $order_price_count = pdo_fetch("SELECT sum(price) as totalPrice FROM `ims_ewei_shop_groups_order` where teamid=25");
                     if( $order_price_count  && !empty($order_price_count) && $order_price_count['totalPrice'] > 0) {
                         $totalPrice = sprintf('%.2f',$order_price_count['totalPrice']); # 保留两位小数 - (数据库已经帮我们整理好了，这里只是为了再次确认下)
                         
                         # 开始计算用户能得到的余额 | 严格按照要求传参 ratio
                         $credit = sprintf('%.2f' , ($totalPrice * $credit));
                     }
                }else{
                    return false;
                }
            }else{
                $credit = sprintf('%d',$credit) < 1 ? 1 : $credit;
            }
            
            m('member')->setCredit($openid , $creditType , $credit);

            return true;
        }
        return false;
    }

    public function test($v = '参数错误')
    {
        echo $v;
    }
    /**
     * 设置满减额度
     * @param string $name 配置参数名称
     * @param string $param 配置参数值
     */
    public function setConfig($name , $param)
    {
        if( !$param || $param < 1 ) {
            return false;
        }
        
        $array = compact('name','param');

        # 写入
        $result = pdo_update('ewei_shop_groups_extend_system' , $array);

        if( !empty($result) ) {
            return true;
        }
        return false;
    }

    /**
     * 读取配置
     * @param string $param 配置参数值
     */
    public function getConfig($name='m_off')
    {
        $param = pdo_fetchcolumn("SELECT `param` FROM ims_ewei_shop_groups_extend_system where name='m_off'");

        return $param ? $param : false;
    }

    /**
     * 获取已经提取余额的订单的信息
     * @param int 可选三个参数 0 => 等待审核 2 审核失败 1 审核成功 3 所有
     */
    public function getOrderExtractedInfo($status=3)
    {
        if( $status == 3 ) {
            $extraedOrders = pdo_fetchall("SELECT * FROM ims_ewei_shop_groups_extend_extracted");
        }else{
            $extraedOrders = pdo_fetchall("SELECT * FROM ims_ewei_shop_groups_extend_extracted where status=:status" , ['status' => $status] , 'id');
        }

        return $extraedOrders;
    }

    /**
     * 显示我的下线参加的团
     * 当用户发起查看我的下线的所有参团的时候，显示他的团的信息(未提现)
     */
    public function getOrderExtractInfo($arr=[])
    {
        $arr = [
            'id' , 'openid' , 'orderno' , 'paytime' , 'pay_type' , 'address' , 'price'
        ];
        $arr = implode(',' , $arr);

        # 获取我的信息
//        $openid =  m('user')->getOpenid();
        $openid = 'sns_wa_ogO535JOR5Fb3G4NuoLW-dd6df7s';

        $id = pdo_fetchcolumn("SELECT id from ims_ewei_shop_member where openid=:openid" , compact('openid'));

        # 查看我的下线
        $subordinates = pdo_fetchall("SELECT b.openid as openid FROM ims_ewei_shop_member as a left join ims_ewei_shop_member as b on a.id = b.agentid where a.id = :id" , compact('id'));
        $subordinates = $this->filter($subordinates);

        # 查看下线的订单（未提取余额的）也就是不在数据表中的
        $orderInfo = pdo_fetchall("select $arr from ims_ewei_shop_groups_order WHERE openid IN ($subordinates) AND id NOT IN (SELECT groups_order_id from ims_ewei_shop_groups_extend_extracted) AND status='-1' AND deleted = 0 AND is_team=1");

        if( !$orderInfo || empty($orderInfo) ) {
            return false;
        }
        return [$orderInfo , $openid];
    }

    /**
     * 发起提取余额后写入审核订单中
     * 必须传入id值 ， 这个表是以订单的id进行保存的
     * @param array $orders 订单号码
     * @param string $openid 谁发起的余额提交
     */
    public function setOrderExtractingInfo($orders , $openid)
    {
        try {
            $time = time();

            if( !$this->isCheckPrice($orders) ) {
                return '必须满足条件哦，才可提取';
            }

            foreach ($orders as $order) {
                # 首先需要查询提取表中是否存在这个订单id，否则不插入
                $extracted = pdo_fetchcolumn("SELECT id FROM ims_ewei_shop_groups_extend_extracted WHERE groups_order_id=:id" , ['id' => $order['id']]);

                if( $extracted ) {
                    continue;
                    # 执行一段插入错误日志
                    error_log('单：提取的时候发送了错误' . serialize($order) , 3 , IA_ROOT . "/log/order2.log" , null);
                }

                $order = $this->preareParamToOrder($order , $openid);
                $order['createtime'] = $time;

                # 插入
                pdo_insert('ewei_shop_groups_extend_extracted' , $order );
            }

            return true;
        }catch (\Exception $e) {
            # 执行一段插入错误日志
            error_log('总：提取的时候发送了错误' . serialize($orders) , 3 , IA_ROOT . "/log/order2.log" , null);

            return false;
        }
    }


    /**
     * 参数过滤
     * @param $params
     * @return bool|string|null
     */
    public function filter($params)
    {
        $str = null;
        foreach ($params as $param) {
            $str .= "'{$param['openid']}',";
        }
        $str = substr($str , 0, strlen($str) -1);
        return $str;
    }


    /**
     * 准备订单数据
     * @param $order
     * @return array
     */
    public function preareParamToOrder($order,$openid)
    {
        $arr = [
            'openid' => $openid,
            'groups_order_id' => $order['id'],
            'price' => $order['price'] ,
            'createtime' => time(),
            'reason' => $order['reason']
        ];

        return $arr;
    }


    /**
     * 显示所有审核订单表中的订单
     * @param int $status
     * @return array
     */
    public function showAudits($status=0)
    {
        $audits = pdo_fetchall("SELECT createtime FROM `ims_ewei_shop_groups_extend_extracted` WHERE status=:status GROUP BY 'createtime'", compact('status'));

        $orders = [];

        foreach ($audits as $key => $audit ){
            $order = pdo_fetchall("SELECT * FROM `ims_ewei_shop_groups_extend_extracted` where createtime=:createtime" , ['createtime' => $audit['createtime']]);
            $orders[$key] = $order;
        }
        return $orders;
    }

    /**
     * 审核用户提交
     * 根据提交的时间来决定审核的订单
     */
    public function auditExtraed($ct,$new_status)
    {
        # 只需要查出一条即可
        $info = pdo_fetch("SELECT status,openid FROM ims_ewei_shop_groups_extend_extracted where createtime=:createtime AND status='0'" , ['createtime' => $ct] );

        $openid = $info['openid'];
        $status = $info['status'];

        # 以及审核的消息不可回退为不审核
        switch ($new_status) {
            case '1' : # 审核成功 , 只能提交的情况下进行审核
                if( $status == 0 || $status = 2  ) {
                    pdo_update('ewei_shop_groups_extend_extracted' , ['status' => 1] , ['createtime' => $ct]);
                    # 增加余额到余额表中(打款日志)
                    return '审核成功,待线下结算';
                }else{
                    return '状态异常';
                }

                break;
            case '2' : # 审核打回
                if( $status == 0 ) {
                    pdo_update('ewei_shop_groups_extend_extracted' , ['status' => 2] , ['createtime' => $ct]);
                }else{
                    return '状态异常';
                }

                return '审核打回';
                break;
            default :
                return '请确认状态';
        }
    }

    public function isCheckPrice($orders)
    {
        $totalPrice = 0;

        // 查询所有订单价格是否达到满减
        foreach ($orders as $order) {
            $totalPrice += $order['price'];
        }

        $endPrice = $this->getConfig();

        if( $totalPrice < $endPrice ) {
            return false;
        }
        return true;
    }
}


    
